package com.tg.demo.web.manage;

import com.github.pagehelper.PageInfo;
import com.tg.demo.common.ConstantUtil;
import com.tg.demo.common.Page;
import com.tg.demo.common.Result;
import com.tg.demo.common.util.StringUtils;
import com.tg.demo.entity.AuthEnum;
import com.tg.demo.entity.User;
import com.tg.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * AuthController
 *
 * @author yuanjin
 * @date 2019/3/29
 */
@Controller
@Slf4j
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private UserService userService;

    /**
     * 跳转到列表页
     *
     * @param model the model
     * @return string string
     */
    @RequestMapping(value = "/gotoListPage", method = {RequestMethod.GET, RequestMethod.POST})
    public String gotoListPage(Model model) {
        return "/auth/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Page list(Page page, User user) {
        user.setRoles(AuthEnum.getListKeyEnum());
        PageInfo<User> info = userService.getListByPage(user, page.getPage(), page.getPageSize());
        Page result = new Page();
        result.setTotal(Integer.parseInt(info.getTotal() + ""));
        result.setRows(info.getList());
        return result;
    }

    /**
     * 保存用户权限
     *
     * @param user the user
     * @return object object
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(@ModelAttribute User user) {
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        if (user != null
                && !StringUtils.isBlank(user.getUserCode())
                && null != user.getRole()) {
            User user1 = User.builder().userCode(user.getUserCode()).build();
            List<User> list = userService.getUserByCondition(user1);
            if (!list.isEmpty() && list.size() == 1) {
                user1.setRole(user.getRole());
                userService.update(user1);
                result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
            }
        }
        return result;
    }
}
